import {
	Api_url
} from './config'

export default {
	async post(url, param, yanci = false) {
		// wx.showLoading();

		// setTimeout(() => {
		// 	wx.hideLoading();
		// }, 3000)
		const res = await this.uni_request(url, param, 'post')

		return res;
	},
	async get(url, param, yanci = false) {
		// wx.showLoading();
		// setTimeout(() => {
		// 	wx.hideLoading();
		// }, 3000)
		const res = await this.uni_request(url, param, 'get')
		return res;
	},
	async put(url, param) {
		// wx.showLoading();
		// setTimeout(() => {
		// 	wx.hideLoading();
		// }, 3000)
		const res = await this.uni_request(url, param, 'put')
		return res;
	},
	uni_request(url, param, method, again_quest = true) {
		const that = this
		uni.showLoading({
			title: '加载中...'
		})
		return new Promise((cback, reject) => {
			uni.request({
				url: Api_url + url,
				data: param,
				method: method,
				header: {
					'Authorization': 'Bearer ' + uni.getStorageSync("token")
				},
			}).then(data => { //data为一个数组，数组第一项为错误信息，第二项为返回数据
				var [error, res] = data;
				var res_code = res.data.code;
				if (res_code === 200) {
					uni.hideLoading();
					cback(res.data);
				}else if (res_code == 401) {
					//登录失效跳转到登录界面
					uni.showToast({
						title: '登录超时',
						icon: 'none'
					});
					if (again_quest) {
						uni.switchTab({
							url: '../../pages/my/my'
						});
					} else {
						console.log('再次登陆仍然失败', url)
					}
				} else {
					console.log('400/500', url, error, res)
					uni.showToast({
						title: res.data.msg ? res.data.msg : '请求异常',
						icon: 'none'
					})
				}
			}).catch(err => {
				console.log('catch:', err);
			})
		})
	},

}
